<template>
  <div id="forumpage"
       :style="{background: 'url('+bgimgBtn+')',backgroundRepeat: 'no-repeat',backgroundSize: '100% 100%'}">
    <div class="forum">
      <forumheader></forumheader>
      <div class="rourmCenter">
        <div class="rourmCenter-centent">
          <div class="centent-two linebox">
            <el-page-header @back="goBack" content="详情" class="mb-20"></el-page-header>
            <div class="centent-two-title">
              <span>文章</span>
              <p>{{detailArticle?detailArticle.title:'--'}}</p>
            </div>
            <div class="centent-two-usertime">
              <span class="mr-20">版主：{{detailArticle?detailArticle.user.realname:'--'}}</span>
              <span>发布时间：{{detailArticle?detailArticle.create_time:'--'}}</span>
            </div>
            <div class="centent-two-desc" v-html="detailArticle.body" v-if="detailArticle">
            </div>
            <div class="centent-two-usertime">
              <span class="mr-20" v-if="detailArticle.type==0">通知范围：全校职工</span>
              <span class="mr-20" v-else>通知范围：{{detailArticle.usersName}}</span>
            </div>
            <div class="centent-two-talk" v-if="detailArticle">
              <p v-if="eximationState">
                <el-button size="small" @click="getqrcode()" type="primary">确定发布</el-button>
                <el-button size="small" @click="detelTearch()">驳回</el-button>
              </p>
              <span class="detailgetzan" v-else @click="laudBtnFn">
                <i class="iconfont iconpraise" :class="is_laud?'activeline':''"></i>{{detailArticle.laud}}
              </span>
            </div>
          </div>
          <div class="centent-commont linebox" v-if="!eximationState">
            <div class="centent-commont-top">
              <div class="commontimg-add mb-10">
                <el-upload
                        class="el-upload-body"
                        :action="$uploadImg"
                        :on-progress="handleProgress"
                        :before-upload="beforeUpload"
                        :on-success="handleAvatarSuccess"
                        :show-file-list="false"
                        drag
                        accept=".jpg,.jpeg,.png"
                        :disabled="commontPic.length<=2?false:true"
                        multiple>
                  <div style="display: flex;align-items: center;">
                  <el-button class="addimgbutton" :disabled="commontPic.length<=2?false:true"><i class="el-icon-picture"></i>添加图片</el-button>
                  <p style="color:#999;font-size: 12px;">(最多三张)</p>
                  </div>
                </el-upload>
                <div class="commontimg-add-list" v-if="commontPic.length">
                  <div :style="{backgroundImage: 'url('+item+')',backgroundRepeat: 'no-repeat'}"
                       class="commontimg-add-list-img" v-for="(item,index) in commontPic" :key="index">
                    <span class="iconfont iconguanbi" @click="detelImgFn(index)"></span>
                  </div>
                </div>
              </div>
              <el-input placeholder="填写评论内容" type="textarea" maxlength="200" show-word-limit
                        v-model="contentVal"></el-input>
              <p class="btncomment">
                <span @click="commentAdd" :class="contentVal!==''?'commentBtn':''">评论</span>
              </p>
            </div>
            <div class="centent-commont-bottom">
              <p class="centent-commont-bottom-title"><span>全部评论({{comment_count}})</span></p>
              <div class="centent-commont-body">
                <div class="centent-commont-list" v-for="(item,index) in commentList" :key="index">
                  <img src="@/assets/imageAdmin/logo.jpg" alt="" class="centent-commont-list-userimg">
                  <div class="centent-commont-list-right">
                    <div class="centent-commont-name">
                      <span class="centent-commont-nameuser">{{item.user?item.user.realname:'匿名'}}</span>
                      <!--<p class="centent-commont-name-article">评论了你的文章 <span class="articlename">《关于疫情后的复课通知》</span></p>-->
                      <span class="centent-commont-time">{{item.create_time}}</span>
                    </div>
                    <p class="centent-commont-word">{{item.content}}</p>
                    <div class="centent-commont-img" v-if="item.piclist.length">
                      <div class="centent-commont-img-list" :style="{backgroundImage: 'url('+(items.indexOf('http://')!==-1?items:imgUploadSrc+items)+')',backgroundRepeat: 'no-repeat'}" v-for="(items,indexs) in item.piclist" :key="indexs" @click="showImageFn(index)"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="rourmCenter-right" v-if="pageOption.type!=='2'">
          <!--<modulelist></modulelist>-->
          <!--<div class="rourmCenter-right-two">-->
          <!--<div class="ponitlist">-->
          <!--<p class="ponitlist-title">昨日文章阅读数</p>-->
          <!--<span class="ponitlist-num">200</span>-->
          <!--<p class="ponitlist-check">较前日<span><i class="iconxiangshangjiantou iconfont"></i>80%</span></p>-->
          <!--</div>-->
          <!--<div class="ponitlist">-->
          <!--<p class="ponitlist-title">昨日评论点赞数</p>-->
          <!--<span class="ponitlist-num">200</span>-->
          <!--<p class="ponitlist-check">较前日<span><i class="iconxiangxiajiantou iconfont"></i>20%</span></p>-->
          <!--</div>-->
          <!--</div>-->
          <div class="rourmCenter-right-one linebox" v-if="detailArticle&&detailArticle.is_parents==1">
            <p class="theme-title">二维码</p>
            <div class="imageDomBody">
              <div class="forumcode savebox" ref="imageDom">
                <!--//applycode-->
                <img src="@/assets/imageAdmin/codebg.png" alt="" class="saveimgBg">
                <div class="apply-code-title">
                  <p class="title-top">今日论坛</p>
                  <p class="title-article">学校：{{schoolinfo?schoolinfo.name:'--'}}</p>
                  <p class="title-article"><span>文章：</span><span>{{detailArticle?detailArticle.title:'--'}}</span></p>
                  <p class="title-article">时间：{{detailArticle?detailArticle.examine_time:'--'}}</p>
                  <div class="title-body">
                  </div>
                  <div class="apply-code-img" v-if="codeQrcode" style="width:220px;">
                    <img :src="codeQrcode" alt="">
                  </div>
                  <p class="getcode">扫码阅读</p>
                </div>
              </div>
            </div>
            <div>
              <img :src="imgUrl" alt="" class="qercodeShow">
              <div class="primaryBtn">
                <el-button type="primary" size="small" @click="downloadIamge">下载二维码</el-button>
              </div>
            </div>
          </div>
          <!--<modulecate></modulecate>-->
        </div>
      </div>
    </div>
    <progressDialog :visible.sync="progressVisible" :progressPercent="progressPercent"></progressDialog>
    <!-- 图片弹窗 -->
    <showimageDialog :showImgObj="showImgObj" :visible.sync="dialogImgVisible"></showimageDialog>
  </div>
</template>

<script>
  import html2canvas from 'html2canvas'
  import bgimgBtn from '@/assets/imageAdmin/bgforue.png'
  import modulecate from '@/components/forum/modulecate'
  import modulelist from '@/components/forum/modulelist'
  import forumheader from '@/components/forum/headerforum'
  import {pagination} from '@/utils/util.js'
  import progressDialog from '@/components/dialog/progressDialog.vue'
  import showimageDialog from '@/components/dialog/showimageDialog.vue'
  import {mapGetters} from "vuex";

  export default {
    components: {
      modulecate,
      modulelist,
      forumheader,
      progressDialog,
      showimageDialog
    },
    data () {
      return {
        dialogImgVisible: false,
        progressVisible: false,
        progressPercent: 0,
        bgimgBtn: bgimgBtn,
        pageOption: this.$route.query,
        page: {
          pageindex: pagination.pageIndex,
          pagesize: pagination.pageSize,
          total: pagination.total
        },
        detailArticle: null,
        eximationState: false,
        comment_count: 0,
        commentList: [],
        is_laud: false, // 是否点赞
        contentVal: '', // 评论内容
        codeQrcode: '',
        imgUrl: '',
        schoolinfo: '学校名称',
        commontPic: [],
        showImgObj: []
      }
    },
    computed: {
      ...mapGetters(['userInfo']),
    },
    created () {
      console.log('pageOption:', this.pageOption)
      let state = false
      if (Number(this.pageOption.type) === 2) {
        state = true
      } else {

      }
      this.eximationState = state
      this.InitFn()
    },
    methods: {
      InitFn () {
        this.$fetch(this.api.forum_postings_edit, {id: this.pageOption.id, p: this.page.pageindex}).then((response) => {
          if (response.code === 0) {
            if(response.vo.type===1){
              let list = [];
              for(let i in response.vo.user_ids){
                list.push(response.vo.user_ids[i].realname)
              }
              response.vo.usersName = list.join(',')
            }
            this.detailArticle = response.vo
            this.comment_count = response.comment_count
            this.is_laud = response.is_laud
            for (let i in response.comment) {
              if (response.comment[i].pic) {
                response.comment[i].piclist = response.comment[i].pic.split(',')
              } else {
                response.comment[i].piclist = []
              }
            }
            this.commentList = response.comment
            console.log(123)
            if (response.vo.is_parents === 1) {
              this.qrcodeGet()
            }
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      qrcodeGet () {
        let self_ = this
        this.$fetch(this.api.forum_postings_qrcode, {id: this.pageOption.id}).then((response) => {
          if (response.code === 0) {
            this.codeQrcode = response.pic
            console.log(123222)
            setTimeout(() => {
              self_.html2canvasFn()
            }, 600)
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      html2canvasFn () {
        let self_ = this
        let opts = {
          useCORS: true
        }
        html2canvas(self_.$refs.imageDom, opts).then(canvas => {
          let image = new Image()
          image.onload = function () {
            self_.imgUrl = canvas.toDataURL('image/png')
            console.log('haole')
            self_.codeloading = false
          }
          image.src = canvas.toDataURL('image/png')
        })
      },
      detelImgFn (index) {
        this.commontPic.splice(index, 1)
      },
      goBack () {
        this.$router.go(-1)
      },
      showImageFn (index) {
        this.showImgObj = this.commentList[index].piclist
        this.dialogImgVisible = true
      },
      laudBtnFn () {
        if (!this.is_laud) {
          console.log('点赞')
          this.$post(this.api.forum_laud_add, {postings_id: this.pageOption.id}).then((response) => {
            if (response.code === 0) {
              this.is_laud = true
              this.detailArticle.laud++
            } else {
            }
          }).catch((err) => {
            console.log(err)
          })
        }
      },
      commentAdd () {
        if (!this.contentVal && !this.commontPic.length) {
          this.$message.error('请填写相应评论内容或相关图片')
          return
        }
        this.$post(this.api.forum_comment_add, {
          postings_id: this.pageOption.id,
          content: this.contentVal,
          pic: this.commontPic.join(',')
        }).then((response) => {
          if (response.code === 0) {
            this.$message({
              message: '评价成功',
              type: 'success'
            })
            this.contentVal = ''
            this.commontPic = []
            this.comment_count++
            this.InitFn()
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      beforeUpload () {
        this.progressVisible = true
      },
      handleProgress (event) {
        this.progressPercent = parseInt(event.percent)
      },
      handleAvatarSuccess (e) {
        let this_ = this
        if (e.code == 0) {
          this.commontPic.push(e.data.name)
          setTimeout(() => {
            this_.progressVisible = false
            this_.progressPercent = 0
          }, 500)
        } else {
          this.$message({
            message: '上传失败',
            type: 'error'
          })
        }
      },
      downloadIamge () { // 下载图片地址和图片名
        let image = new Image()// 解决跨域 Canvas 污染问题
        let this_ = this
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function () {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据

          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          // this.infoForm.title
          // 'codetype', // codetype: 1, // 1 通知 2 问卷
          a.download = '论坛' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src = this.imgUrl
      },
      getqrcode () {
        this.$confirm('确定通过审核，发布该版块文章?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.checkSuccessFn()
        }).catch(() => {

        })
      },
      checkSuccessFn () {
        // 0待审核1审核2驳回 is_examine
        this.$post(this.api.forum_postings_adopt, {
          id: this.pageOption.id
        }).then((response) => {
          if (response.code === 0) {
            this.$message({
              message: '发布成功',
              type: 'success'
            })
            this.$router.go(-1)
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      detelTearch () {
        this.$prompt('请填写相应的驳回理由，以便记录更改', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          console.log('输入的内容：', value)
          if (!value) {
            this.$message.error('请填写相应的驳回理由')
          } else {
            this.checkFailFn(value)
          }
        }).catch(() => {
        })
      },
      checkFailFn (value) {
        // 0待审核1审核2驳回 is_examine
        this.$post(this.api.forum_postings_reject, {
          id: this.arryList[index].id,
          content: value
        }).then((response) => {
          if (response.code === 0) {
            this.$message({
              message: '驳回成功',
              type: 'success'
            })
            this.$router.go(-1)
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    mounted () {
    }
  }
</script>


